import * as React from 'react';

import {IView} from '../types/IView';
import {IParentView} from '../types/IParentView';
import {IAttr} from '../types/IAttr';

import {IViewObject} from './IViewObject';
import AbsParentViewObject from './AbsParentViewObject';

import textViewObject from './TextViewObject';
import divViewObject from './DivViewObject';

export class TabItemViewObject extends AbsParentViewObject<IParentView> implements IViewObject<IParentView> {

  viewType = 'tabItem';

  attrs: IAttr[] = [
    {
      name: 'id',
      display: 'ID',
      type: 'string',
      required: true,
      defaultValGenerator: () => {
        return `tabItemView${this.viewIndex}`;
      }
    },
    {
      name: 'className',
      display: 'class',
      type: 'string',
      required: false,
      defaultValGenerator: () => {
        return '';
      }
    }
  ];

  create(designId: string): IParentView {
    return {
      id: this.generateId(),
      viewType: this.viewType,
      designId,
      style: {},
      attrVals: this.createAttrVals(this.attrs),
      children: [
        // 直接添加两个子组件, 一个是标题, 一个是内容
        textViewObject.create(designId),
        divViewObject.create(designId)
      ]
    };
  }

  render(view: IParentView, refUpdater: (view: IView, ref: Element) => void): JSX.Element | null {
    const {attrVals} = view;

    const elemRefUpdater: React.Ref<Element> = el => refUpdater(view, el);
    const props: React.HTMLAttributes<HTMLElement> = {
      id: attrVals.id,
      className: attrVals.className,
      style: attrVals.className ? {} : view.style
    };

    // 这里只显示第二个子组件(也就是内容组件), 标题组件会在TabPane 那里进行显示
    return (
      <div ref={elemRefUpdater} {...props}>
        {this.renderChild(view.children[1], refUpdater)}
      </div>
    );
  }

  /**
   * 不能再添加子组件了, 要添加也只能往内容子组件添加了
   * @param childViewType
   * @returns {boolean}
   */
  accept(childViewType: string): boolean {
    return false;
  }

  /**
   * 因为不能再添加子组件, 所以已有的子组件也不能被删除
   * @param childViewIndex
   * @returns {boolean}
   */
  preventDeleteChild(childViewIndex: number): boolean {
    return true;
  }
}

const tabItemViewObject = new TabItemViewObject();
export default tabItemViewObject;


